package com.nf;

import com.nf.handler.Constants;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class MiniBasicRowProcessor implements MiniRowProcessor {

    //调用BeanProcessor的转换器进行转换toBean对象
    public MiniBeanProcessor convert=null;

    public MiniBasicRowProcessor() {
        this(Constants.DEFAULT_BEAN_PROCESSOR);
    }

    public MiniBasicRowProcessor(MiniBeanProcessor convert) {
        super();
        this.convert=convert;
    }

    @Override
    public Object[] toArray(ResultSet rs) throws SQLException {
        //获取结果集元素，可以获取到列的数量
        ResultSetMetaData metaData = rs.getMetaData();
        //获取查询sql中的字段数量
        int count = metaData.getColumnCount();
        Object[] result=new Object[count];
        for (int i = 0; i < count; i++) {
            result[i]=rs.getObject(i+1);
        }

        return result;
    }

    @Override
    public Map<String, Object> toMap(ResultSet rs) throws SQLException {
        Map<String, Object> map=new HashMap<>();
        ResultSetMetaData metaData = rs.getMetaData();
        int count = metaData.getColumnCount();
        for (int i = 0; i < count; i++) {
            Object filedValue = rs.getObject(i + 1);
            String filedName = metaData.getColumnName(i + 1);
            if (filedName == null || filedName.length()==0) {
                //表明字段别名无法取到，就用列名
                filedName=metaData.getColumnName(i+1);
            }
            map.put(filedName.toLowerCase(),filedValue);
        }
        return map;
    }

    @Override
    public <T> T toBean(ResultSet rs, Class<? extends T> type) throws SQLException {
        return this.convert.toBean(rs,type);
    }
}
